package com.ruoyi.boss.controller;




import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.boss.alipay.AliPayConfig;

import com.ruoyi.boss.domain.TOrder;
import com.ruoyi.boss.mapper.TOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    AliPayConfig aliPayConfig;

    @Autowired
    private TOrderMapper tOrderMapper;
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(String orderNum, HttpServletResponse httpResponse) throws Exception {
        //查询订单号
        TOrder tOrder=tOrderMapper.selectTOrderByPay(orderNum);
        if (tOrder == null) {
            throw new RuntimeException("订单不存在: " + orderNum);
        }
        //1.创建Client,通用SDK提供的Client,负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        //2.创建Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", tOrder.getOrderNumber());
        bizContent.put("total_amount", tOrder.getOrderPrice());
        bizContent.put("subject", "充值");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:9301/alipay/pay");
        //执行请求,拿到响应的结果,返回给浏览器
        String form="";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset="+CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();



    }
  /**
   * @description 异步回调
   * @author FZY
   * @date 2025/8/26 18:46
   * @version 1.0
   */
    @PostMapping("/notify")
    public void notify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("支付宝异步回调");
            HashMap<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()){
                params.put(name, request.getParameter(name));
            }
            String sign=params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8");
            if(checkSignature){
                //验签通过
                System.out.println("交易名称:"+params.get("subject"));
                System.out.println("交易状态:"+params.get("trade_status"));
                System.out.println("支付宝交易号:"+params.get("order_number"));
                System.out.println("商户订单号:"+params.get("out_trade_no"));
                System.out.println("付款金额:"+params.get("total_amount"));
                System.out.println("买家在在支付宝唯一id"+params.get("buyer_id"));
                System.out.println("买家付款时间:"+params.get("gmt_payment"));
                System.out.println("买家付款金额:"+params.get("buyer_pay_amount"));

                //订单编号
                String orderNum = params.get("order_number");
                //支付时间
                String gmtPayment = params.get("gmt_payment");
                //支付宝交易账号
                String alipayTrade = params.get("order_number");

               TOrder tOrder = tOrderMapper.selectTOrderByPay(orderNum);
                //更新订单状态为已支付,设置支付信息
                tOrder.setPayTime(new Date());
                tOrder.setTradeNumber("完成"+orderNum);
                tOrderMapper.updateByPay(tOrder);
            }
        }

    }
}
